'use strict';

const Service = require('egg').Service;
const fs = require('fs');
const path = require('path');
// 故名思意 异步二进制 写入流
const awaitWriteStream = require('await-stream-ready').write;
// 管道读入一个虫洞。
const sendToWormhole = require('stream-wormhole');
const dayjs = require('dayjs');
const uuidV4 = require('uuid/v4');

class UserSettService extends Service {
  async img_upload(fileStream, id) {
    const {
      ctx,
    } = this;
    ctx.logger.debug('-----------获取数据 start--------------');
    ctx.logger.debug(fileStream.fields);
    ctx.logger.debug('-----------获取数据 end--------------');
    // 基础的目录
    const uplaodBasePath = 'F:/Graduation/antagraduation/public/uploads';
    // 生成文件名
    const fileName = uuidV4() + path.extname(fileStream.filename).toLocaleLowerCase();
    // 生成文件夹
    const dirname = dayjs(Date.now()).format('YYYY/MM/DD');

    function mkdirsSync(dirname) {
      if (fs.existsSync(dirname)) {
        return true;
      }
      if (mkdirsSync(path.dirname(dirname))) {
        fs.mkdirSync(dirname);
        return true;
      }

    }
    ctx.logger.debug('>>>>>>>>>>>  储存数据 <<<<<<<<<<<<<<<');
    mkdirsSync(path.join(uplaodBasePath, dirname));
    // 生成写入路径
    const target = path.join(uplaodBasePath, dirname, fileName);
    // 写入流
    const writeStream = fs.createWriteStream(target);
    try {
      // 异步把文件流 写入
      await awaitWriteStream(fileStream.pipe(writeStream));
    } catch (err) {
      // 如果出现错误，关闭管道
      await sendToWormhole(fileStream);
      return {
        status: 400,
        data: {
          msg: '上传错误，请重新再试',
        },
      };
    }
    ctx.model.User.update({
      userimg: path.join('/uploads', dirname, fileName),
    }, {
      where: {
        id,
      },
    });
    const user = JSON.parse(await this.app.redis.get(id + 'u'));
    user.userimg = path.join('/uploads', dirname, fileName);
    this.app.redis.setex(id + 'u', 60 * 30, JSON.stringify(user));
    return {
      status: 200,
      data: {
        msg: '上传成功',
        imgurl: path.join('/uploads', dirname, fileName),
      },
    };
  }
  async setNickName(newNickNameInfo) {
    const {
      ctx,
    } = this;
    const whIs = await ctx.model.User.findOne({
      where: {
        nickname: newNickNameInfo.newNickName,
      },
    });
    if (!whIs) {
      const result = await ctx.model.User.update(
        {
          nickname: newNickNameInfo.newNickName,
        },
        {
          where: {
            id: newNickNameInfo.id,
          },
        }
      );
      if (result) {
        const redisUser = JSON.parse(await this.app.redis.get(newNickNameInfo.id + 'u'));
        redisUser.nickname = newNickNameInfo.newNickName;
        this.app.redis.setex(newNickNameInfo.id + 'u', 60 * 30, JSON.stringify(redisUser));
        return {
          status: 200,
          data: {
            msg: '修改用户名成功',
          },
        };
      }
      return {
        status: 400,
        data: {
          msg: '修改用户名失败',
        },
      };
    }
    return {
      status: 401,
      data: {
        msg: '此用户名已存在',
      },
    };
  }
  async setOther(userInfo) {
    const { ctx } = this;
    const result = await ctx.model.User.update(
      {
        username: userInfo.name,
        sex: userInfo.sex,
        birthday: userInfo.birthday,
        provinceaddress: userInfo.province,
        cityaddress: userInfo.city,
        areaaddress: userInfo.county,
        hobby: JSON.stringify(userInfo.happle),
      },
      {
        where: {
          id: userInfo.userid,
        },
      }
    );
    if (result) {
      const redisUser = JSON.parse(await this.app.redis.get(userInfo.userid + 'u'));
      redisUser.username = userInfo.name;
      redisUser.sex = userInfo.sex;
      redisUser.birthday = userInfo.birthday;
      redisUser.provinceaddress = userInfo.province;
      redisUser.cityaddress = userInfo.city;
      redisUser.areaaddress = userInfo.county;
      redisUser.hobby = JSON.stringify(userInfo.happle);
      await this.app.redis.setex(userInfo.userid + 'u', 60 * 30, JSON.stringify(redisUser));
      return {
        status: 200,
        data: {
          msg: '用户信息修改成功',
        },
      };
    }
    return {
      status: 400,
      data: {
        msg: '用户信息修改失败',
      },
    };
  }
}
module.exports = UserSettService;
